<template>
    <div class="app-container">
        <el-card class="operate-container" shadow="never">
            <i class="el-icon-tickets" style="margin-top: 5px"></i>
            <span style="margin-top: 5px">数据列表</span>
            <el-button
                    class="btn-add"
                    @click="handleAddMenu"
                    size="mini">
                添加
            </el-button>
        </el-card>

        <div class="table-container">
            <el-table ref="menuTable"
                      style="width: 100%"
                      :data="list"
                      v-loading="listLoading" border>
                <el-table-column label="编号" width="100" align="center">
                    <template #default="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column label="菜单名称" align="center">
                    <template #default="scope">{{ scope.row.title }}</template>
                </el-table-column>
                <el-table-column label="菜单级数" width="100" align="center">
                    <template #default="scope">{{ levelFilter(scope.row.level) }}</template>
                </el-table-column>
                <el-table-column label="前端名称" align="center">
                    <template #default="scope">{{ scope.row.name }}</template>
                </el-table-column>
                <el-table-column label="前端图标" width="100" align="center">
                    <template #default="scope"><svg-icon :icon-class="scope.row.icon"></svg-icon></template>
                </el-table-column>
                <el-table-column label="是否显示" width="100" align="center">
                    <template #default="scope">
                        <el-switch
                                @change="handleHiddenChange(scope.$index, scope.row)"
                                :active-value="0"
                                :inactive-value="1"
                                v-model="scope.row.hidden">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="app端是否显示" width="100" align="center">
                    <template #default="scope">
                        <el-switch
                                @change="handleAppStatusChange(scope.$index, scope.row)"
                                :active-value="0"
                                :inactive-value="1"
                                v-model="scope.row.appStatus">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="排序" width="100" align="center">
                    <template #default="scope">{{ scope.row.sort }}</template>
                </el-table-column>
                <el-table-column label="设置" width="120" align="center">
                    <template #default="scope">
                        <el-button
                                size="mini"
                                type="text"
                                :disabled="disableNextLevel(scope.row.level)"
                                @click="handleShowNextLevel(scope.$index, scope.row)">
                            查看下级
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template #default="scope">
                        <el-button
                                size="mini"
                                type="text"
                                @click="handleUpdate(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="text"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="pagination-container">
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    layout="total, sizes, prev, pager, next, jumper"
                    :page-size="listQuery.pageSize"
                    :page-sizes="[10, 15, 20]"
                    v-model:current-page="listQuery.pageNum"
                    :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import { ref, reactive, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fetchList, deleteMenu, updateHidden, updateAppStatus } from '@/api/menu';

export default {
    name: "menuList",
    setup() {
        const route = useRoute();
        const router = useRouter();
        const list = ref([]);
        const total = ref(0);
        const listLoading = ref(true);
        const listQuery = reactive({
            pageNum: 1,
            pageSize: 5
        });
        const parentId = ref(0);

        const resetParentId = () => {
            listQuery.pageNum = 1;
            parentId.value = route.query.parentId || 0;
        };

        const getList = async () => {
            listLoading.value = true;
            try {
                const response = await fetchList(parentId.value, listQuery);
                list.value = response.data.data.list;
                total.value = response.data.data.total;
            } catch (error) {
                console.error('Error fetching list:', error);
            } finally {
                listLoading.value = false;
            }
        };

        const handleAddMenu = () => {
            router.push('/employeeManagement/addMenu');
        };

        const handleSizeChange = (val) => {
            listQuery.pageNum = 1;
            listQuery.pageSize = val;
            getList();
        };

        const handleCurrentChange = (val) => {
            listQuery.pageNum = val;
            getList();
        };

        const handleHiddenChange = async (index, row) => {
            try {
                await updateHidden(row.id, { hidden: row.hidden });
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                    duration: 1000
                });
            } catch (error) {
                console.error('Error updating hidden status:', error);
                ElMessage({
                    message: '修改失败，请重试',
                    type: 'error',
                    duration: 1000
                });
            }
        };

        // 新增的方法来处理 app 状态的改变
        const handleAppStatusChange = async (index, row) => {
            try {
                await updateAppStatus(row.id, { appStatus: row.appStatus });
                ElMessage({
                    message: 'app端显示状态修改成功',
                    type: 'success',
                    duration: 1000
                });
            } catch (error) {
                console.error('Error updating app status:', error);
                ElMessage({
                    message: '修改失败，请重试',
                    type: 'error',
                    duration: 1000
                });
            }
        };

        const handleShowNextLevel = (index, row) => {
            router.push({ path: '/employeeManagement/menu', query: { parentId: row.id } });
        };

        const handleUpdate = (index, row) => {
            router.push({ path: '/employeeManagement/updateMenu', query: { id: row.id } });
        };

        const handleDelete = async (index, row) => {
            try {
                await ElMessageBox.confirm('是否要删除该菜单', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                await deleteMenu(row.id);
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                    duration: 1000
                });
                await getList();
            } catch (error) {
                if (error.message !== 'cancel') {
                    console.error('Error deleting menu:', error);
                    ElMessage({
                        message: '删除失败，请重试',
                        type: 'error',
                        duration: 1000
                    });
                }
            }
        };

        // Filters
        const levelFilter = (value) => {
            return value === 0 ? '一级' : value === 1 ? '二级' : '';
        };

        const disableNextLevel = (value) => {
            return value !== 0;
        };

        // Lifecycle hooks
        onMounted(() => {
            resetParentId();
            getList();
        });

        watch(route, () => {
            resetParentId();
            getList();
        });

        return {
            list,
            total,
            listLoading,
            listQuery,
            parentId,
            resetParentId,
            getList,
            handleAddMenu,
            handleSizeChange,
            handleCurrentChange,
            handleHiddenChange,
            handleShowNextLevel,
            handleUpdate,
            handleDelete,
            levelFilter,
            disableNextLevel,
            handleAppStatusChange // 返回新的处理方法
        };
    }
};
</script>

<style scoped>
/* Add your styles here */
</style>
